const mongoose = require('mongoose');
var User =  mongoose.model('user');
console.log('in controller')

exports.findAllUser = function(req,res){
	User.find(function(err,users){
		if(!err){
			res.json(users);
		}else{
			res.json({error: "findUsers"});
		}
	})
}
exports.addUser = function(req,res){
	var u = new User(req.body);
	console.log(req.body);
	u.save(function(err){
		if(!err){
			res.json(u);
		}else{
			res.json({error: "addUser"});
		}
	})
}
exports.loadUser = function(req,res){
	User.findOne({_id:req.params.id},function(err,user){
		if(!err){
			res.json(user);
		}else{
			res.json({error: "loadUser"});
		}
	})
}
exports.deleteUser = function(req,res){
	User.remove({_id:req.params.id},function(err){
		if(!err){
			res.json({});
		}else{
			res.json({error:'deleteUser'});
		}
	})
}
exports.updateUser = function(req,res){
	
	User.findByIdAndUpdate(req.params.id,req.body,function(err,oldUser){
		if (!err) {
			req.body.id = req.params.id;
			res.json(req.body);
		}else{
			res.json({error: "updateUser"});
		}
	})
}


exports.goTemp =function (req,res) {
	var users = {users:[{uname:"jhon",age:100},{uname:"burgess",age:100}]}
	res.render("tpls",users);
}